package com.naja.auth2clientfirst.support;

import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;

import java.util.HashSet;
import java.util.List;

/**
 * @auther wangjianying
 * @date 2023/12/27 09:19
 */
public class ExpandAuthorityJwtAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {
    ExpandUserAuthoritiesRepository userAuthoritiesRepository = ExpandUserAuthoritiesRepository.instance();

    private JwtAuthenticationConverter delegate = new JwtAuthenticationConverter();
    @Override
    public AbstractAuthenticationToken convert(Jwt jwt) {
        AbstractAuthenticationToken convert = delegate.convert(jwt);
        String name = convert.getName();
        List<String> userAuthoritiesRepositoryByName = userAuthoritiesRepository.findByName(name);
        HashSet<GrantedAuthority> grantedAuthorities = new HashSet<>();
        grantedAuthorities.addAll(convert.getAuthorities());
        for (String s : userAuthoritiesRepositoryByName) {
            grantedAuthorities.add(new SimpleGrantedAuthority(s));
        }
        return new JwtAuthenticationToken(jwt, grantedAuthorities, convert.getName());
    }

}
